package com.kawins.util;

import tk.mybatis.mapper.entity.Example;

/**
 * @author rankai
 *         createTime 2018-01-2018/1/18 20:38
 */
public class SortUtil {

    /**
     * 数据库排序
     * 使用示例:
     * Example example = new Example(CmDefFun.class);
     * Example.Criteria criteria = example.createCriteria();
     * criteria.andEqualTo("parentId", parentId);
     * int impairment = sortImpairment(shorts, oldSorts, isDel, criteria);
     * List<CmDefFun> defFunList = selectByExample(example);
     * if (defFunList.size() != 0) {
     * for (CmDefFun defFun : defFunList) {
     * defFun.setShorts(defFun.getShorts() + impairment);
     * updateByPrimaryKeySelective(defFun);
     * }
     * }
     *
     * @param newSort   新位置
     * @param oldSort   旧位置
     * @param isDel     是否是删除
     * @param criteria  Example.Criteria
     * @param shortName 模型中排序字段名
     * @return
     */
    public static int sortImpairment(Integer newSort, Integer oldSort, boolean isDel,
                                     Example.Criteria criteria, String shortName) {
        int impairment = 1;
        if (oldSort == null) {
            if (isDel) {
                impairment = -1;
            }
            criteria.andGreaterThanOrEqualTo(shortName, newSort);
        } else {
            if (newSort > oldSort) {
                criteria.andBetween(shortName, oldSort + 1, newSort);
                impairment = -1;
            } else {
                criteria.andBetween(shortName, newSort, oldSort - 1);
            }
        }
        return impairment;
    }

}
